package per.lance.easytomcat.handler;

import per.lance.easytomcat.net.HttpRequest;
import per.lance.easytomcat.net.HttpRespone;
import per.lance.easytomcat.util.FileUtil;
import per.lance.easytomcat.env.StatusCodes;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

public class StaticHandler implements Handler{

    public void doStaticHandler(HttpRequest httpRequest, HttpRespone httpRespone) {
        try {
            String filePath = "";
            File file = null;
            Map<String, String> map = FileUtil.getRedirectProperties("config/redirect.properties");
            if (StatusCodes.ERROR.equals(httpRespone.getStatusCode())) {
                filePath = getStaticFilePath("static/views/500.html");
                file = new File(filePath);
                httpRespone.getResponeHeader().clear();
            } else if (map.containsKey(httpRequest.getUri().getPath())) {
                httpRespone.setStatusCode(StatusCodes.REDIRECT);
                httpRespone.getResponeHeader().put("Location", map.get(httpRequest.getUri().getPath()));
                httpRespone.respone();
                return;
            } else {
                filePath = getStaticFilePath(httpRequest.getUri().getPath());
                file = new File(filePath);
                if (!file.exists()) {
                    filePath = getStaticFilePath("static/views/404.html");
                    file = new File(filePath);
                    httpRespone.setStatusCode(StatusCodes.NOTFOUND);
                } else {
                    httpRespone.setStatusCode(StatusCodes.SUCCESS);
                }
            }
            Path path = Paths.get(filePath);
            String contentType = Files.probeContentType(path);
            httpRespone.getResponeHeader().put("Content-Type", contentType);
            httpRespone.setResponeBody(FileUtil.toByteArray(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getStaticFilePath(String requestPath) {
        String rootPath = this.getClass().getResource("/").getPath();
        rootPath = rootPath.substring(1, rootPath.length());
        return rootPath + requestPath;
    }

}
